package com.gyz.cfmall.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.gyz.cfmall.feign.MemberFeignService;
import com.gyz.cfmall.vo.SocialUser;
import com.gyz.common.utils.HttpUtils;
import com.gyz.common.utils.R;
import com.gyz.common.vo.MemberResponseVo;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * @author gong_yz
 * @Description
 * @Date 2023/4/10
 */
@Controller
@Slf4j
public class OAuth2Controller {

    @Resource
    private MemberFeignService memberFeignService;

    @GetMapping("/oauth2.0/gitee/success")
    public String gitee(@RequestParam("code") String code, HttpSession session) throws Exception {
        Map<String, String> headers = new HashMap<>();
        Map<String, String> querys = new HashMap<>();
        querys.put("client_id", "33bc7c489583b275e20737b0a730f85a768a26aadd4f006195429d254e55911f");
        querys.put("client_secret", "23b278e8483e21710101edb7b45a1e45cca5c7281d175268b5fa4123d33c71f0");
        querys.put("grant_type", "authorization_code");
        querys.put("redirect_uri", "http://auth.cfmall.com/oauth2.0/gitee/success");
        querys.put("code", code);
        Map<String, String> bodys = new HashMap<>();
        HttpResponse response = HttpUtils.doPost("https://gitee.com", "/oauth/token", "post", headers, querys, bodys);
        if (response.getStatusLine().getStatusCode() == 200) {
            //状态响应码为200则为成功
            String json = EntityUtils.toString(response.getEntity());
            SocialUser socialUser = JSON.parseObject(json, new TypeReference<SocialUser>() {
            });
            socialUser.setUuid(UUID.randomUUID().toString());
            System.out.println(socialUser);
            //知道了哪个社交用户
            //1）、当前用户如果是第一次进网站，自动注册进来（为当前社交用户生成一个会员信息，以后这个社交账号就对应指定的会员）
            //登录或者注册这个社交用户
            System.out.println(socialUser.getAccess_token());
            //调用远程服务
            R oauthLogin = memberFeignService.oauthLogin(socialUser);
            if (oauthLogin.getCode() == 0) {
                MemberResponseVo data = oauthLogin.getData("data", new TypeReference<MemberResponseVo>() {
                });
                log.info("登录成功：用户信息：{}", data.toString());

                session.setAttribute("loginUser", data);
                //2、登录成功跳回首页
                return "redirect:http://cfmall.com";
            } else {
                return "redirect:http://auth.cfmall.com/login.html";
            }

        } else {
            return "redirect:http://auth.cfmall.com/login.html";
        }
    }

}
